"""
录音例子的UI层。
"""
import glob
from typing import Any, Final
import os
from elio import core

# 接收到的录音文件存放到服务器，并以静态文件发送到客户端播放
localBaseUrl = core.static_file_serve('', '/static')
uploadBaseUrl = core.file_upload_serve('', '/upload')
# 录音文件的格式
MEDIA_FORMAT: Final[str] = 'aac'


class RecorderLayer(core.AutoRecycleLayer[core.Activity]):
    recorder: core.MediaRecorder = None
    player: core.MediaPlayer = None
    layout: core.ColumnLayout = None

    async def on_create(self, *args: Any, **kwargs: dict):
        await super().on_create(*args, *kwargs)

    async def on_show(self):
        await super().on_show()
        activity = self.parent

        self.recorder = await core.MediaRecorder.create(activity, MEDIA_FORMAT)
        self.player = await core.MediaPlayer.create(activity)
        await self.player.load_from_media_recorder(self.recorder)
        self.layout = await core.ColumnLayout.create(activity)
        wb_record = await self.layout.add(core.WidgetButton, .1, widget_args=('开始录音',))
        wb_pause = await self.layout.add(core.WidgetButton, .1, widget_args=('暂停录音',))
        wb_upload = await self.layout.add(core.WidgetButton, .1, widget_args=('上传录音',))
        await wb_pause.set_enabled(False)
        is_recording, is_paused = False, False

        async def cb_record():
            """
            录音按钮点击事件。
            """
            nonlocal is_recording, is_paused
            is_paused = False
            await wb_pause.set_text('暂停录音')
            if is_recording:
                if await self.recorder.stop():
                    print(await self.recorder.get_filename())
                    await self.player.play()
                else:
                    print("Error: No record Data")

                await wb_record.set_text('开始录音')
            else:
                await self.recorder.start()
                await wb_record.set_text('停止录音')

            is_recording = not is_recording
            await wb_pause.set_enabled(is_recording)

        await wb_record.set_on_click_listener(cb_record)

        async def cb_pause():
            """
            暂停录音按钮点击事件。
            """
            nonlocal is_paused
            if is_paused:
                await self.recorder.resume()
                await wb_pause.set_text('暂停录音')
            else:
                await self.recorder.pause()
                await wb_pause.set_text('继续录音')
            is_paused = not is_paused

        await wb_pause.set_on_click_listener(cb_pause)

        async def cb_upload():
            """
            上传按钮点击事件。
            """
            async def cb_progress(progress: float):
                """
                上传进度事件。
                :param progress: 进度值。
                """
                print('已上传%.2f%%' % progress)
            await self.recorder.upload(uploadBaseUrl, cb_progress)
            print('上传完毕。')
        await wb_upload.set_on_click_listener(cb_upload)

    async def on_hide(self):
        await super().on_hide()
        if self.recorder:
            await self.recorder.destroy()
        if self.player:
            await self.player.destroy()
        if self.layout:
            await self.layout.destroy()

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def on_destroy(self, *args: Any, **kwargs: dict):
        for file in glob.glob('*.' + MEDIA_FORMAT):
            os.unlink(file)
        await super().on_destroy(*args, **kwargs)
